package com.meviewer.activity.file.browser;

import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.cardview.widget.CardView;

import com.google.common.collect.Lists;
import com.meviewer.R;
import com.meviewer.activity.BaseActivity;
import com.meviewer.activity.MainActivity;
import com.meviewer.common.Constants;

import java.io.File;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author hanhaoran
 */
public class FileBrowserGridViewAdapter extends BaseAdapter {

    private static final String ROOT_PATH = "/storage/emulated/0";

    private static final String BACK = "返回上一级";

    private BaseActivity activity;
    private TextView tv;

    private String base;

    private String catalog;
    private boolean checkcatalog;
    private boolean isRoot;
    private List<String> rootpathlist;
    private boolean isFile;
    private String jsContextFunctionName;
    private List<String> filenames;

    public FileBrowserGridViewAdapter(BaseActivity activity, TextView tv, boolean isFile, String rootPath, boolean pathAll, String jsContextFunctionName) {
        this.activity = activity;
        this.tv = tv;
//        this.base = pathAll ? ROOT_PATH : rootPath;
        this.base = ROOT_PATH;
       this.catalog = rootPath;
        this.isFile = isFile;
        this.isRoot = true;
        this.checkcatalog = false;
        this.jsContextFunctionName = jsContextFunctionName;

        updateFiles(new File(catalog));
        updateTextView();

    }

    @Override
    public int getCount() {
        return filenames.size();
    }

    @Override
    public Object getItem(int i) {
        return filenames.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = LayoutInflater.from(activity).inflate(R.layout.rvi_file_browser_item, viewGroup, false);
        }

        ViewHolder holder = new ViewHolder(view);
        if (i == 0) {
            holder.iv.setImageResource(R.drawable.ic_back);
            holder.tv.setText(BACK);
            holder.cv.setOnClickListener(v -> back2Parent());

        } else {
            File file = new File(filenames.get(i));
            holder.iv.setImageResource(file.isDirectory() ? R.drawable.ic_folder : R.drawable.ic_file);
            holder.tv.setText(file.getName());

            holder.cv.setOnClickListener(v -> {
                if (file.isDirectory()) {
                    catalog += (Constants.SEPARATOR_SLASH + file.getName());
                    updateFiles(file);
                    updateTextView();
                    notifyDataSetChanged();
                } else {
                    if (isFile) {
                        Intent back = new Intent();
                        back.putExtra(FileBrowserActivity.ARG_FILEPATH, file.getAbsolutePath());
                        back.putExtra(FileBrowserActivity.JS_CONTEXT_FUNCTION_NAME, jsContextFunctionName);
                        activity.setResult(FileBrowserActivity.ACTION_LOAD_FILE_BROWSER_CODE, back);
                        activity.finish();
                    }
                }
            });
        }
        return view;
    }

    public void back2Parent() {

        for (String path:this.rootpathlist) {
            if (path.equals(catalog))
            {
                this.isRoot=true;
            }
        }
        if(this.isRoot)
        {
            catalog=ROOT_PATH;;
            updateTextView();
            updateFiles(new File(catalog));
            notifyDataSetChanged();
            Toast.makeText(activity, "已经是顶层目录", Toast.LENGTH_SHORT).show();

        }else {
            this.checkcatalog = false;
            catalog = catalog.substring(0, catalog.lastIndexOf(Constants.SEPARATOR_SLASH));
            updateTextView();
            updateFiles(new File(catalog));
            notifyDataSetChanged();
        }
    }

    public String getCatalog() {
        return catalog;
    }

    private void updateTextView() {
        this.tv.setText(this.catalog);
    }

    private void updateFiles(File file) {
        File[] children;
        this.catalog =String.valueOf(file);

        if(this.isRoot)
        {
            List<File> list = new ArrayList<File>();
            File[] tschildren =MainActivity.getInstance().getExternalFilesDirs(Environment.MEDIA_MOUNTED);
            this.rootpathlist = Lists.newArrayList();
            for( File filed:tschildren){
                String m_string = String.valueOf(filed).trim().substring(0, String.valueOf(filed).indexOf("Android")-1) ;
                rootpathlist.add(m_string);
                File f = new File(m_string);
                list.add(f);
            }
            this.checkcatalog =true;
            children =  list.toArray(new File[0]);
        }else
        {
            children = file.listFiles();
        }

        filenames = Lists.newArrayList(BACK);
        if (children != null) {
        Arrays.sort(children, Comparator.comparing(File::getName));
        Arrays.stream(children).forEach(f -> filenames.add(f.getAbsolutePath()));
        }
        this.isRoot =false;
    }

    static class ViewHolder {
        CardView cv;
        ImageView iv;
        TextView tv;

        public ViewHolder(View view) {
            this.cv = view.findViewById(R.id.rvi_cv);
            this.iv = view.findViewById(R.id.rvi_iv);
            this.tv = view.findViewById(R.id.rvi_tv);
        }
    }
}
